package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/category")
@RestController
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> insert(@RequestBody Category category) {
        log.info("现在玩的是添加操作");
        categoryService.save(category);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        //分页构造器
        Page<Category> page1 = new Page<>(page, pageSize);
        //System.out.println("高铂汶插死你"+page1.toString());

        //条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        wrapper.orderByAsc(Category::getSort);
        //分页查询操作
        categoryService.page(page1, wrapper);
        return R.success(page1);
    }
    @DeleteMapping
    public R<String> delete(Long id){
        categoryService.delete(id);
        return R.success("删除成功");
    }
    @PutMapping
    public R<String> update(@RequestBody Category category){

        categoryService.updateById(category);
        return R.success("修改成功");
    }

    //前端传来的参数只是type=1   我们要打开格局
    // category中的所有包括type 所以参数可以传category
    @GetMapping("/list")
public R<List<Category>> select(Category category) {

    LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
    //有条件的查询,所以需要条件构造器;

    //给wrpper加条件
    // wrapper.eq(Category::getType,category.getType());
     wrapper.eq(category.getType()!=null,Category::getType,category.getType());
    //添加排序条件
     wrapper.orderByAsc(Category::getSort);
    //最后展开查询所有
    List<Category> list = categoryService.list(wrapper);

    //返回值为一个list集合  所以
   return R.success(list);
}
}
